package com.example.ordersystem.controller;

import com.example.ordersystem.entity.User;
import com.example.ordersystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class RegisterController {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    @PostMapping("/register")
    public String doRegister(@RequestParam String username, @RequestParam String password) {
        System.out.println("注册请求：" + username + " / " + password);
        try {
            if (userRepository.findByUsername(username) != null) {
                System.out.println("用户已存在：" + username);
                return "register";
            }
            User user = new User();
            user.setUsername(username);
            user.setPassword(passwordEncoder.encode(password));
            userRepository.save(user);
            System.out.println("注册成功：" + username);
            return "redirect:/login";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("注册异常：" + e.getMessage());
            return "register";
        }
    }
} 